﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EPiServer.Data.Dynamic;

namespace EPiServer.Research.PageProviders
{
    public class MappedPageStore
    {
        protected static MappedPageStore _instance;

        public static MappedPageStore Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new MappedPageStore();
                }
                return _instance;
            }
        }

        protected DynamicDataStore _store;
        public MappedPageStore()
        {
            _store= DynamicDataStoreFactory.Instance.GetStore(typeof(MappedPage)) ?? DynamicDataStoreFactory.Instance.CreateStore(typeof(MappedPage));
        }

        public MappedPage AddKey(string Provider, string Key)
        {
            MappedPage mp = new MappedPage();
            mp.PageKey = Key;
            mp.ProviderID = Provider;
            mp.PageGuid = Guid.NewGuid();
            mp.PageID = _store.Items<MappedPage>().Count() + 1;
            _store.Save(mp);
            return mp;
        }

        public MappedPage LoadMapping(string Provider, Guid g)
        {
            return _store.Items<MappedPage>().Where(mp => mp.ProviderID==Provider && mp.PageGuid == g).FirstOrDefault();
        }

        public MappedPage LoadMapping(string Provider, int Id)
        {
            return _store.Items<MappedPage>().Where(mp => mp.ProviderID == Provider && mp.PageID == Id).FirstOrDefault();
        }

        public MappedPage LoadMapping(string Provider, string Key)
        {
            var rt= _store.Items<MappedPage>().Where(mp => mp.ProviderID == Provider && mp.PageKey == Key).FirstOrDefault();
            if (rt == null) rt = AddKey(Provider, Key);
            return rt;
        }
    }
}
